package com.wy.panda.common.bean.converter;

import java.util.ArrayList;
import java.util.List;

import com.wy.panda.common.page.PageResult;
import com.wy.panda.common.util.CollectionUtils;

import lombok.NoArgsConstructor;
import ma.glasnost.orika.CustomConverter;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;

/**
 * 
 *
 * @param <S>
 * @param <D>
 * @author WangYuan
 * @since 2020年9月7日 下午4:56:05
 */
@NoArgsConstructor
public class PageResultConverter<S, D> extends CustomConverter<PageResult<S>, PageResult<D>> {

	@Override
	public PageResult<D> convert(PageResult<S> source, Type<? extends PageResult<D>> destinationType,
			MappingContext mappingContext) {
		List<D> destinationData = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(source.getData())) {
		    java.lang.reflect.Type sourceActualType = mappingContext.getResolvedSourceType().getActualTypeArguments()[0];
		    java.lang.reflect.Type destinationActualType = mappingContext.getResolvedDestinationType().getActualTypeArguments()[0];
		    
			destinationData = mapperFacade.mapAsList(source.getData(), TypeFactory.valueOf(sourceActualType), TypeFactory.valueOf(destinationActualType));
		}
		
		return PageResult.build(destinationData, source.getTotal(), source.getSize(), source.getCurrent());
	}

	@Override
	public boolean canConvert(Type<?> sourceType, Type<?> destinationType) {
		return PageResult.class.equals(sourceType.getRawType()) && PageResult.class.equals(destinationType.getRawType());
	}
}
